<?php
/**
 * 与"Creole 解析器（改进版）"配合使用的编辑器
 * 可输入Tab,插入Creole格式的附件和图片链接
 *
 * @package CrackEditor
 * @author John.H
 * @version 1.0.0
 * @link http://typecho.org
 */
class CrackEditor_Plugin implements Typecho_Plugin_Interface
{
    public static function activate()
    {
        Typecho_Plugin::factory('admin/write-post.php')->richEditor = array('CrackEditor_Plugin', 'editor');
    }

    public static function deactivate(){}

    public static function config(Typecho_Widget_Helper_Form $form){}

    public static function personalConfig(Typecho_Widget_Helper_Form $form){}

    public static function editor($post)
    {
        $autoSave           = $post->options->autoSave ? 'true' : 'false';
        $autoSaveLeaveMsg   = '您的内容尚未保存, 是否离开此页面?';
        $resizeUrl          = '/action/ajax';
        echo <<<EOF
<script type="text/javascript">
(function(){
    var isIE = Browser.Engine.trident;

    function textareaInsert(field, instr){
		if (isIE) {
			//For IE
			field.focus();
			var sel  = document.selection.createRange();
            document.selection.clear();
			sel.text = instr;
			return false;
		}
		else if (Browser.Engine.gecko || Browser.Engine.webkit) {
			//For Firefox/Safari/Chrome
			var startPos = field.selectionStart;
			var endPos 	 = field.selectionEnd;
			field.value  = [
				field.value.substring(0, startPos),
				instr,
				field.value.substring(endPos, field.value.length)
			].join('');
			var oriPos = startPos + instr.length;
			field.selectionStart = oriPos;
			field.selectionEnd	 = oriPos;
			return false;
		}
		else {
			//For other not support browsers
			//alert('Not support');
			return true;
		}
	}

    var textEditor = new Typecho.textarea('#text', {
        autoSaveTime: 15,
        resizeAble: true,
        autoSave: '{$autoSave}',
        autoSaveMessageElement: 'auto-save-message',
        autoSaveLeaveMessage: '{$autoSaveLeaveMsg}',
        resizeUrl: '{$resizeUrl}'
    });

    textEditor.simpleInsert = function(instr){
        var range  = (null == this.range) ? this.textarea.getSelectedRange() : this.range,
            field  = this.textarea,
            text   = field.get('value'),
            prefix = text.substr(0, range.start),
            suffix = text.substr(range.end);
        field.set('value', prefix + instr + suffix);
        field.focus();
        field.selectRange(range.start + instr.length, range.start + instr.length);
        this.recordRange();
    };

	textEditor.textarea.addEvents({
		keydown: (function (evt) {
         	var field = this.textarea;
         	if (evt.code === 9) {
         		var instr = '\t';
         		return textareaInsert(field, instr);
         	}
		}).bind(textEditor)
	});

    /** 这两个函数在插件中必须实现 */
    window.insertImageToEditor = function (title, url, link) {
        var instr = ['\\n{{',url,'|',title,'}}\\n'].join('');
        textEditor.simpleInsert(instr);
        /*
        if(isIE){
            textEditor.setContent(['\\n{{',url,'|',title,'}}\\n'].join(''), '');
        }
        else{
            var instr = ['\\n{{',url,'|',title,'}}\\n'].join('');
            textareaInsert(textEditor.textarea, instr);
        }
        */
        new Fx.Scroll(window).toElement($(document).getElement('textarea#text'));
    };

    window.insertLinkToEditor = function (title, url, link) {
    	textEditor.setContent(['[[',url,'|',title,']]'].join(''), '');
        new Fx.Scroll(window).toElement($(document).getElement('textarea#text'));
    };
})();
</script>
EOF;
    }

}